package controllers

import (
	"context"
	beego "github.com/beego/beego/v2/server/web"
	"shops/cache"
	"shops/models"
	"shops/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "用户名或密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var u models.User
	u.Username = username
	u.Password = pkg.Md5(password)
	err := u.Create()
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "注册成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	key := "login_fail" + username
	count, _ := cache.Rdb.Get(context.Background(), key).Int()
	if count >= 3 {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "账号已锁定，请稍后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if username == "" || password == "" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "用户名或密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var u models.User
	err := u.GetInfoByUser(username)
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "登录失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if u.ID == 0 {
		cache.Rdb.Incr(context.Background(), key).Result()
		if count == 2 {
			cache.Rdb.Expire(context.Background(), key, 60*time.Second)
		}
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	password = pkg.Md5(password)
	if u.Password != password {
		cache.Rdb.Incr(context.Background(), key).Result()
		if count == 2 {
			cache.Rdb.Expire(context.Background(), key, 60*time.Second)
		}
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "登录成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
